package com.hlcl.huaji.view;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;

import com.cjj.MaterialRefreshLayout;
import com.cjj.MaterialRefreshListener;
import com.elcl.activity.fragment.BaseFragment;
import com.elcl.util.ListUtils;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.hlcl.huaji.R;
import com.hlcl.huaji.ctrl.adapter.OrderListAdapter;
import com.hlcl.huaji.ctrl.toast.SuccessToastUtils;
import com.hlcl.huaji.model.LoginResult;
import com.hlcl.huaji.model.Order;
import com.hlcl.huaji.model.OrderResult;
import com.hlcl.huaji.server.NetCode;
import com.hlcl.huaji.server.OrderServer;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by lichunlin on 2018/5/17.
 * 订单的fragment
 */

public class OrderFragment extends BaseFragment implements View.OnClickListener {

    public int position;//0为最新 1、全部 2、待处理 3、处理中  4、已完成

    //1、未抢单(快速抢修)   2、未抢单(预约维修)  3、已抢单（待处理）4、（处理中）5、待评价
    // 6、已完成（维修成功）7、已取消 8、维修失败 0是全部
    private int orderType = 0;

    public static HomeFragment homeFragment;

    public static OrderFragment getInstance(int position, HomeFragment homeFragment) {
        OrderFragment orderFragment = new OrderFragment();
        OrderFragment.homeFragment = homeFragment;
        orderFragment.position = position;
        return orderFragment;
    }

    View view;

    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        view = LayoutInflater.from(getActivity()).inflate(R.layout.fra_order, null);

        initOrderType();
        getOrderListServer();
        initView();
        initListView();
        return view;
    }

    //初始化订单
    private void initOrderType() {
        if (position == 0) {
            orderType = 1;
        } else if (position == 1) {//全部
            orderType = 10;
        } else if (position == 2) {//待处理
            orderType = 3;
        } else if (position == 3) {//处理中
            orderType = 4;
        } else if (position == 4) {//已完成
            orderType = 12;
        }else if(position == 5){//已评价
            orderType = 11;
        }
    }

    public boolean isNeedRefresh = true;//是否需要刷新

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (isVisibleToUser && isNeedRefresh) {
            getOrderListServer();
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        if (isNeedRefresh){
            getOrderListServer();
        }
    }

    private ListView lv_content;
    private View emptyView;
    private TextView tv_empty, tv_repair_quickly, tv_repair_date;
    private View view_empty;

    private void initView() {
        initRefreshLayout();
        lv_content = (ListView) view.findViewById(R.id.lv_content);
        emptyView = LayoutInflater.from(getActivity()).inflate(R.layout.view_empty, null);
        lv_content.addFooterView(emptyView);

        tv_empty = emptyView.findViewById(R.id.tv_empty);
        view_empty = emptyView.findViewById(R.id.view_empty);

        tv_repair_quickly = view.findViewById(R.id.tv_repair_quickly);
        tv_repair_date = view.findViewById(R.id.tv_repair_date);

        if (position == 0) {//如果是最新
            setVisibility(view, R.id.ll_order_type, View.VISIBLE);
            tv_repair_quickly.setOnClickListener(this);
            tv_repair_date.setOnClickListener(this);
        } else {
            setVisibility(view, R.id.ll_order_type, View.GONE);
        }
    }

    private OrderListAdapter orderListAdapter;
    private List<Order> orderListAll = new ArrayList<>();

    private void initListView() {
        if (null != lv_content) {
            if (null == orderListAdapter) {
                orderListAdapter = new OrderListAdapter(orderListAll, R.layout.adapter_order);
                orderListAdapter.setOrderType(orderType);
                lv_content.setAdapter(orderListAdapter);
                lv_content.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                    @Override
                    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                        openActivityByType(orderListAll.get(position).getOrderid());
                    }
                });
                orderListAdapter.setOnItemClickListener(new OrderListAdapter.OnItemClickListener() {
                    @Override
                    public void onClickListener(int position) {
                        OrderServer.getInstance().modifyOrderServer(netHandler
                                , orderListAll.get(position).getOrderid()
                                , 3);
                    }
                });
            } else {
                orderListAdapter.notifyDataSetChanged();
            }
        }
    }

    private void initViewEmpty() {
        if (ListUtils.isEmpty(orderListAll)) {
            view_empty.setVisibility(View.VISIBLE);
            tv_empty.setVisibility(View.VISIBLE);
        } else {
            view_empty.setVisibility(View.GONE);
            tv_empty.setVisibility(View.GONE);
        }
    }

    //根据activity打开activity
    private void openActivityByType(String orderId) {
        Intent intent = new Intent(getActivity(), OrderDetailActivity.class);
        intent.putExtra("orderId", orderId);
        startActivity(intent);

    }

    private MaterialRefreshLayout materialRefreshLayout;

    private void initRefreshLayout() {
        materialRefreshLayout = (MaterialRefreshLayout) view.findViewById(R.id.refreshlayout);
        materialRefreshLayout.setMaterialRefreshListener(new MaterialRefreshListener() {
            @Override
            public void onRefresh(final MaterialRefreshLayout materialRefreshLayout) {
                pageNo = 1;
                getOrderListServer();
            }

            @Override
            public void onRefreshLoadMore(MaterialRefreshLayout materialRefreshLayout) {
                pageNo++;
                getOrderListServer();
            }
        });
        materialRefreshLayout.setLoadMore(true);
    }

    private int pageNo = 1;

    //获取订单的server
    private void getOrderListServer() {
        isNeedRefresh = false;
        OrderServer.getInstance().getOrderListServer(netHandler, orderType, pageNo);
    }

    private Gson gson = new Gson();

    @Override
    protected void praseJson(int reqId, String json) {
        materialRefreshLayout.finishRefreshing();
        materialRefreshLayout.finishRefreshLoadMore();
        if (reqId == NetCode.ID_ORDER_LIST) {//订单列表
            if (pageNo == 1) {
                orderListAll.clear();
            }
            OrderResult orderResult = gson.fromJson(json, new TypeToken<OrderResult>() {
            }.getType());
            if (null != orderResult && null != orderResult.getjData()) {
                List<Order> orders = orderResult.getjData().getJsonArrayResult();
                orderListAll.addAll(orders);
                orderListAdapter.notifyDataSetChanged();
            }
            initViewEmpty();
        } else if (reqId == NetCode.ID_ORDER_MODIFY_STATE) {//抢单成功
            pageNo = 1;
            SuccessToastUtils.showToast("恭喜您接单成功");
            refreshOrderList();
            getOrderListServer();
        }
    }

    private void refreshOrderList() {
        OrderFragment orderFragment2 = (OrderFragment) HomeFragment.homeFragment.pagerAdapter.getItem(1);
        orderFragment2.isNeedRefresh = true;

        OrderFragment orderFragment3 = (OrderFragment) HomeFragment.homeFragment.pagerAdapter.getItem(2);
        orderFragment3.isNeedRefresh = true;
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_repair_quickly://快速维修
                setClickViewChange(0);
                break;
            case R.id.tv_repair_date://预约维修
                setClickViewChange(1);
                break;
        }
    }

    //点击button的效果
    private void setClickViewChange(int type) {
        pageNo = 1;
        if (type == 0) {//快速维修
            orderType = 1;
            tv_repair_quickly.setTextColor(getResources().getColor(R.color.white));
            tv_repair_quickly.setBackgroundColor(getResources().getColor(R.color.color_yellow));
            tv_repair_date.setTextColor(getResources().getColor(R.color.text_black));
            tv_repair_date.setBackgroundColor(getResources().getColor(R.color.white));
        } else if (type == 1) {//预约维修
            orderType = 2;
            tv_repair_quickly.setTextColor(getResources().getColor(R.color.text_black));
            tv_repair_quickly.setBackgroundColor(getResources().getColor(R.color.white));
            tv_repair_date.setTextColor(getResources().getColor(R.color.white));
            tv_repair_date.setBackgroundColor(getResources().getColor(R.color.color_yellow));
        }
        getOrderListServer();
    }


}
